package pl.druminski.robinhood.updater.controller;

import java.util.logging.Logger;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import pl.druminski.robinhood.updater.model.Data;
import pl.druminski.robinhood.updater.model.Update;

/**
 * @author Łukasz Drumiński
 * 
 */
public class XMLDataLoader
{
    private Data data;
    private DocumentBuilderFactory factory;
    private DocumentBuilder builder;
    private Document doc;

    public XMLDataLoader(Data data)
    {
        this.data = data;

        factory = DocumentBuilderFactory.newInstance();
        try
        {
            builder = factory.newDocumentBuilder();
        } catch (ParserConfigurationException ex)
        {
            Logger.getLogger(data.getLogName()).warning("Problem z parserem xml. " + ex.getMessage());
        }

    }

    private void addUpdate(String url, String dest)
    {
        StringBuilder name = new StringBuilder(url);
        int i = url.lastIndexOf('/');
        name.delete(0, i+1);
        Update update = new Update(name.toString(), url, dest);
        data.updates.add(update);
    }

    public void loadData()
    {
        String url=null;
        String dest=null;

        try
        {
            doc = builder.parse(data.getUpdateFile());
        } catch (Exception ex)
        {
            Logger.getLogger(data.getLogName()).warning("Problem z parserem xml. " + ex.getMessage());
        }

        Element root = doc.getDocumentElement();

        NodeList children = root.getChildNodes();

        for (int i = 0; i < children.getLength(); i++)
        {
            Node child = children.item(i);

            if (child instanceof Element)
            {
                if (child.getNodeName().equals("update"))
                {
                    NodeList childs = child.getChildNodes();
                    for (int j = 0; j < childs.getLength(); j++)
                    {
                        child = childs.item(j);
                        if (child instanceof Element)
                        {
                            if (child.getNodeName().equals("url"))
                            {
                                url = child.getFirstChild().getTextContent();
                            } else if (child.getNodeName().equals("dest"))
                            {
                                dest = child.getFirstChild().getTextContent();
                            }
                        }
                    }

                    addUpdate(url, dest);

                }
            }
        }
    }
}
